﻿using System;
using System.Configuration;
using System.IO;
using Autofac;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using Module = Autofac.Module;

namespace WinformDevelopFrame.Core.Autofac
{
    public class AutofacModuleRegister: Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            var basePath = AppContext.BaseDirectory;
            var dataAccess = Assembly.GetExecutingAssembly();
            #region 带有接口层的服务注入
            var servicesDllFile = Path.Combine(basePath, "WinformDevelopFrame.Services.dll");
            var repositoryDllFile = Path.Combine(basePath, "WinformDevelopFrame.Repository.dll");

            if (!(File.Exists(servicesDllFile) && File.Exists(repositoryDllFile)))
            {
                var msg = "Repository.dll和Services.dll 丢失，因为项目解耦了，所以需要先F6编译，再F5运行，请检查 bin 文件夹，并拷贝。";
                throw new Exception(msg);
            }
            // 获取 Service.dll 程序集服务，并注册
            var assemblysServices = Assembly.LoadFrom(servicesDllFile);
            //支持属性注入依赖重复
            builder.RegisterAssemblyTypes(assemblysServices).AsImplementedInterfaces().InstancePerDependency()
                .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);

            // 获取 Repository.dll 程序集服务，并注册
            var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
            //支持属性注入依赖重复
            builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces().InstancePerDependency()
                .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
            #endregion

            #region 注册界面
            //获取所有窗体类型
            var baseType = typeof(System.Windows.Forms.Form);
            builder.RegisterAssemblyTypes(Assembly.LoadFrom("WinformDevelopFrame.dll"))
                .Where(t => baseType.IsAssignableFrom(t) && t != baseType).AsImplementedInterfaces()
                .InstancePerDependency()
                .Named(t => t.Name, typeof(System.Windows.Forms.Form));
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["FormDll"]))
            {
                var dlls = ConfigurationManager.AppSettings["FormDll"].Split(";");
                foreach (var dll in dlls)
                {
                    var d = Assembly.LoadFrom(Application.StartupPath + dll);
                    builder.RegisterAssemblyTypes(d)
                        .Where(t => baseType.IsAssignableFrom(t) && t != baseType).AsImplementedInterfaces()
                        .InstancePerDependency()
                        .Named(t => t.Name, typeof(System.Windows.Forms.Form));
                    //支持属性注入依赖重复
                    builder.RegisterAssemblyTypes(d).AsImplementedInterfaces().InstancePerDependency()
                        .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
                }
            }
            #endregion
        }
    }
}
